package br.com.furb.larcmsg.bean;

import java.io.IOException;
import java.net.UnknownHostException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotBlank;

import br.com.furb.larcmsg.controller.Controller;
import br.com.furb.larcmsg.exception.UsuarioInvalidoException;


@ManagedBean
@SessionScoped
public class LoginBean {

	@NotNull(message="informe um id")
	private Integer id;
	
	@NotBlank(message="informe a senha")
	private String senha;
	
	private boolean mostrarMsg;
	
	public void login() throws UnknownHostException, IOException{
		try {
			new Controller(id,senha).buscaUsuarios();
			FacesContext fc = FacesContext.getCurrentInstance();
			ExternalContext ec = fc.getExternalContext();
			ec.redirect(ec.getRequestContextPath() + "/faces/chat.xhtml");
		} catch(UsuarioInvalidoException ex) {
			mostrarMsg = true;
		}
	}
	
	public boolean init() {
		if(!FacesContext.getCurrentInstance().isPostback()) {
			limpar();
		}
		
		return false;
	}
	
	private void limpar() {
		id = null;
		senha = null;
		mostrarMsg = false;
	}
	
	public void logout() throws IOException {
		limpar();
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		ec.redirect(ec.getRequestContextPath() + "/faces/login.xhtml");
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getSenha() {
		return senha;
	}
	public void setSenha(String senha) {
		this.senha = senha;
	}
	public boolean isMostrarMsg() {
		return mostrarMsg;
	}
	public void setMostrarMsg(boolean mostrarMsg) {
		this.mostrarMsg = mostrarMsg;
	}
}
